<?php

/* FUNCIONES Y METODOS QUE ESTAN RELACIONADOS CON EL REGISTRO DE NUEVOS USUARIOS EN FIRST TUESDAY */

/* Reemplaza y modifica al metodo bp_core_screen_signup() de Buddypress para el registro de nuevos usuarios por uno ad hoc a los requerimientos de First Tuesday (registro de usuarios por blog) */

function FT_Registro_Usuario() {
	global $ft, $bp, $wpdb;

	if ($bp->current_component != BP_REGISTER_SLUG)
		return false;

	/* If the user is logged in, redirect away from here */
	if (is_user_logged_in())
		bp_core_redirect($bp->root_domain);

	/***
	 * For backwards compatibility with the old pre 1.1 two theme system, skip this screen function
	 * if the user is using the old two theme method.
	 */
	if(file_exists(WP_CONTENT_DIR.'/bp-themes'))
		return false;

	/* If signups are disabled, just re-direct */
	if('none' == bp_get_signup_allowed() || 'blog' == bp_get_signup_allowed())
		bp_core_redirect($bp->root_domain);

	$bp->signup->step = 'request-details';

	/* If the signup page is submitted, validate and save */
	if(isset( $_POST['signup_submit'])) :

		/* Check the nonce */
		check_admin_referer('bp_new_signup');

		require_once(ABSPATH.WPINC.'/registration.php');

		/* Check the base account details for problems */
		$account_details = wpmu_validate_user_signup($_POST['signup_username'], $_POST['signup_email']);

		/* If there are errors with account details, set them for display */
		if(!empty($account_details['errors']->errors['user_name']))
			$bp->signup->errors['signup_username'] = $account_details['errors']->errors['user_name'][0];

		if(!empty($account_details['errors']->errors['user_email']))
			$bp->signup->errors['signup_email'] = $account_details['errors']->errors['user_email'][0];

		/* Check that both password fields are filled in */
		if(empty($_POST['signup_password']) || empty($_POST['signup_password_confirm']))
			$bp->signup->errors['signup_password'] = __('Please make sure you enter your password twice', 'buddypress');

		/* Check that the passwords match */
		if((!empty( $_POST['signup_password']) && !empty($_POST['signup_password_confirm'])) && $_POST['signup_password'] != $_POST['signup_password_confirm'])
			$bp->signup->errors['signup_password'] = __('The passwords you entered do not match.', 'buddypress');

		/* Comprobando que exista una seleccion de blogs (ciudades) en donde registrar */
		$blogs = FT_Blogs_Sitio();
	
		$blogs_id = array();
		
		if(!empty($_POST['blog_'.$ft->blog_id]))
			$blogs_id[] = $_POST['blog_'.$ft->blog_id];
			
		foreach($blogs as $blog) :
			if(!empty($_POST['blog_'.$blog['blog_id']]) && $_POST['blog_'.$blog['blog_id']] != $ft->blog_id) :
				$blogs_id[] = $_POST['blog_'.$blog['blog_id']];
			endif;
		endforeach;
		
		if(empty($blogs_id))
			$bp->signup->errors['ft_blogs'] = __('This is a required field', 'buddypress');
			
		/* Now we've checked account details, we can check profile information */
		$profile_field_ids = explode(',', $_POST['signup_profile_field_ids']);

		/* Loop through the posted fields formatting any datebox values then validate the field */
		foreach((array)$profile_field_ids as $field_id) :
			if(!isset( $_POST['field_'.$field_id])) :
				if(isset( $_POST['field_'.$field_id.'_day']))
					$_POST['field_'.$field_id] = strtotime($_POST['field_'.$field_id.'_day'].$_POST['field_'.$field_id.'_month'].$_POST['field_'.$field_id.'_year']);
			endif;

			if(xprofile_check_is_required_field($field_id) && empty($_POST['field_'.$field_id]))
				$bp->signup->errors['field_'.$field_id] = __('This is a required field', 'buddypress');
		endforeach;

		/* Finally, let's check the blog details, if the user wants a blog and blog creation is enabled */
		if(isset($_POST['signup_with_blog'])) :
			$active_signup = get_site_option('registration');

			if('blog' == $active_signup || 'all' == $active_signup) :
				$blog_details = wpmu_validate_blog_signup($_POST['signup_blog_url'], $_POST['signup_blog_title']);

				/* If there are errors with blog details, set them for display */
				if(!empty( $blog_details['errors']->errors['blogname']))
					$bp->signup->errors['signup_blog_url'] = $blog_details['errors']->errors['blogname'][0];

				if(!empty( $blog_details['errors']->errors['blog_title']))
					$bp->signup->errors['signup_blog_title'] = $blog_details['errors']->errors['blog_title'][0];
			endif;
		endif;

		do_action('bp_signup_validate');

		/* Add any errors to the action for the field in the template for display. */
		if(!empty( $bp->signup->errors)) :
			foreach($bp->signup->errors as $fieldname => $error_message)
				add_action('bp_'.$fieldname.'_errors', create_function('', 'echo "<div class=\"error\">'.$error_message.'</div>";'));
		else :
			$bp->signup->step = 'save-details';

			/* No errors! Let's register those deets. */
			$active_signup = get_site_option('registration');

			if('none' != $active_signup) :

				/* Let's compact any profile field info into usermeta */
				$profile_field_ids = explode(',', $_POST['signup_profile_field_ids']);

				/* Loop through the posted fields formatting any datebox values then add to usermeta */
				foreach((array)$profile_field_ids as $field_id) :
					if(!isset($_POST['field_'.$field_id])) :
						if(isset($_POST['field_'.$field_id.'_day']))
							$_POST['field_'.$field_id] = strtotime($_POST['field_'.$field_id.'_day'].$_POST['field_'.$field_id.'_month'].$_POST['field_'.$field_id.'_year']);
					endif;

					if(!empty($_POST['field_'.$field_id]))
						$usermeta['field_'.$field_id] = $_POST['field_'.$field_id];
				endforeach;

				/* Store the profile field ID's in usermeta */
				$usermeta['profile_field_ids'] = $_POST['signup_profile_field_ids'];

				/* Hash and store the password */
				$usermeta['password'] = wp_hash_password($_POST['signup_password']);
				
				/* Guarda los ID's de los blogs en que el usuario se registrara una vez que haya activado su cuenta */
				$usermeta['blogs_id'] = implode(',', $blogs_id).','.$ft->site_id;

				/* If the user decided to create a blog, save those details to usermeta */
				if ('blog' == $active_signup || 'all' == $active_signup) :
					$usermeta['public'] = ('public' == $_POST['signup_blog_privacy']) ? true : false;
				endif;

				$usermeta = apply_filters('bp_signup_usermeta', $usermeta);

				/* Finally, sign up the user and/or blog*/
				if(isset($_POST['signup_with_blog']))
					wpmu_signup_blog($blog_details['domain'], $blog_details['path'], $blog_details['blog_title'], $_POST['signup_username'], $_POST['signup_email'], $usermeta);
				else
					wpmu_signup_user($_POST['signup_username'], $_POST['signup_email'], $usermeta);

				$bp->signup->step = 'completed-confirmation';
			endif;

			do_action('bp_complete_signup');
		endif;

	endif;

	$bp->avatar_admin->step = 'upload-image';

	/* If user has uploaded a new avatar */
	if(!empty($_FILES)) :

		/* Check the nonce */
		check_admin_referer('bp_avatar_upload');

		$bp->signup->step = 'completed-confirmation';

		/* Get the activation key */
		if (!$bp->signup->key = $wpdb->get_var( $wpdb->prepare("SELECT activation_key FROM {$wpdb->signups} WHERE user_login = %s AND user_email = %s", $_POST[ 'signup_username' ], $_POST[ 'signup_email' ]))) :
			bp_core_add_message(__('There was a problem uploading your avatar, please try uploading it again', 'buddypress'));
		else :
			/* Hash the key to create the upload folder (added security so people don't sniff the activation key) */
			$bp->signup->avatar_dir = wp_hash($bp->signup->key);

			/* Pass the file to the avatar upload handler */
			if(bp_core_avatar_handle_upload($_FILES, 'bp_core_signup_avatar_upload_dir')) :
				$bp->avatar_admin->step = 'crop-image';

				/* Make sure we include the jQuery jCrop file for image cropping */
				add_action('wp', 'bp_core_add_jquery_cropper');
			endif;
		endif;
	endif;

	/* If the image cropping is done, crop the image and save a full/thumb version */
	if(isset($_POST['avatar-crop-submit'])) :

		/* Check the nonce */
		check_admin_referer('bp_avatar_cropstore');

		/* Reset the avatar step so we can show the upload form again if needed */
		$bp->signup->step = 'completed-confirmation';
		$bp->avatar_admin->step = 'upload-image';

		if(!bp_core_avatar_handle_crop(array('original_file' => $_POST['image_src'], 'crop_x' => $_POST['x'], 'crop_y' => $_POST['y'], 'crop_w' => $_POST['w'], 'crop_h' => $_POST['h'])))
			bp_core_add_message(__( 'There was a problem cropping your avatar, please try uploading it again', 'buddypress' ), 'error');
		else
			bp_core_add_message(__( 'Your new avatar was uploaded successfully', 'buddypress'));

	endif;
	bp_core_load_template('registration/register');
}
remove_action('wp', 'bp_core_screen_signup', 3);
add_action('wp', 'FT_Registro_Usuario', 3);

/* Reemplaza y modifica al metodo bp_core_screen_activation() de Buddypress para la activacion de nuevos usuarios por uno ad hoc a los requerimientos de First Tuesday (registro de usuarios por blog) */

function FT_Activacion_Usuario() {
	global $ft, $bp, $wpdb;

	if(BP_ACTIVATION_SLUG != $bp->current_component)
		return false;

	/* If we are using a BuddyPress 1.0 theme ignore this. */
	if(file_exists(WP_CONTENT_DIR.'/bp-themes'))
		return false;

	/* Check if an activation key has been passed */
	if(isset($_GET['key'])) :

		require_once(ABSPATH.WPINC.'/registration.php');

		/* Activate the signup */
		$signup = apply_filters('bp_core_activate_account', wpmu_activate_signup($_GET['key']));

		/* If there was errors, add a message and redirect */
		if($signup->errors) :
			bp_core_add_message(__('There was an error activating your account, please try again.', 'buddypress'), 'error');
			bp_core_redirect(FT_URL_Activacion_Usuario(false));
		endif;

		/* Set the password */
		if(!empty($signup['meta']['password']))
			$wpdb->update($wpdb->users, array('user_pass' => $signup['meta']['password']), array('ID' => $signup['user_id']), array('%s'), array('%d'));

		/* Set any profile data */
		if(function_exists('xprofile_set_field_data')) :

			if(!empty($signup['meta']['profile_field_ids'])) :
				$profile_field_ids = explode(',', $signup['meta']['profile_field_ids']);

				foreach($profile_field_ids as $field_id) :
					$current_field = $signup['meta']["field_{$field_id}"];

					if(!empty($current_field))
						xprofile_set_field_data($field_id, $signup['user_id'], $current_field);
				endforeach;
			endif;

		endif;
		
		/* Agregando usuario a los blogs que se ha registrado */
		if(!empty($signup['meta']['blogs_id'])) :
				$blogs_id = explode(',', $signup['meta']['blogs_id']);
				
				foreach($blogs_id as $blog_id) :
					if(get_site_option('dashboard_blog') != false)
						add_user_to_blog($blog_id, $signup['user_id'], get_site_option('default_user_role', 'subscriber'));
					elseif($blog_id != $ft->site_id)
						add_user_to_blog($blog_id, $signup['user_id'], get_site_option('default_user_role', 'subscriber'));
				endforeach;
				
				update_usermeta($signup['user_id'], 'primary_blog', $blogs_id[0]);
		endif;

		/* Check for an uploaded avatar and move that to the correct user folder */
		$hashed_key = wp_hash($_GET['key']);

		/* Check if the avatar folder exists. If it does, move rename it, move it and delete the signup avatar dir */
		if(file_exists(WP_CONTENT_DIR.'/blogs.dir/'.BP_ROOT_BLOG.'/files/avatars/signups/'.$hashed_key))
			@rename(WP_CONTENT_DIR.'/blogs.dir/'.BP_ROOT_BLOG.'/files/avatars/signups/'.$hashed_key, WP_CONTENT_DIR.'/blogs.dir/'.BP_ROOT_BLOG.'/files/avatars/'.$signup['user_id']);
		
		/* Record the new user in the activity streams */
		if(function_exists('bp_activity_add')) :
			$userlink = bp_core_get_userlink($signup['user_id']);

			bp_activity_add(array(
				'user_id' => $signup['user_id'],
				'content' => apply_filters('bp_core_activity_registered_member', sprintf(__('%s became a registered member', 'buddypress'), $userlink), $signup['user_id']),
				'primary_link' => apply_filters('bp_core_actiivty_registered_member_primary_link', $userlink),
				'component_name' => 'profile',
				'component_action' => 'new_member'
			));
		endif;

		do_action('bp_core_account_activated', &$signup, $_GET['key']);
		bp_core_add_message(__('Your account is now active!', 'buddypress'));

		$bp->activation_complete = true;
	endif;

	if ('' != locate_template(array('registration/activate'), false))
		bp_core_load_template(apply_filters('bp_core_template_activate', 'activate'));
	else
		bp_core_load_template(apply_filters('bp_core_template_activate', 'registration/activate'));
}
remove_action('wp', 'bp_core_screen_activation', 3);
add_action('wp', 'FT_Activacion_Usuario', 3);
?>